package com.pulsar.controller;

import com.pulsar.entity.Order;
import com.pulsar.entity.OrderRel;
import com.pulsar.entity.User;
import com.pulsar.entity.vo.GoodsVo;
import com.pulsar.message.ResponseCode;
import com.pulsar.redis.RedisClient;
import com.pulsar.service.GoodsService;
import com.pulsar.service.OrderService;
import com.pulsar.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/seckill")
public class SeckillController {

    @Autowired
    RedisClient redisClient;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    SeckillService seckillService;

    @RequestMapping("/do")
    public String list(Model model, User user, @RequestParam("goodsId") long goodsId) {
        model.addAttribute("user", user);
        if (user == null) {
            return "login";
        }

        // 判断库存
        GoodsVo goods = goodsService.getGoodsVoById(goodsId);
        int stock = goods.getSeckillStockCount();
        if (stock <= 0) {
            model.addAttribute("errmsg", ResponseCode.SECKILL_OVER.getMsg());
            return "seckill_fail";
        }

        // 判断是否已经秒杀到了
        OrderRel orderRel = orderService.getOrderRelByUserIdAndGoodsId(user.getUserId(), goodsId);
        if (orderRel != null) {
            model.addAttribute("errmsg", ResponseCode.SECKILL_REPEATE.getMsg());
            return "seckill_fail";
        }

        // 减库存 下订单 写入秒杀订单
        Order order = seckillService.seckill(user, goods);
        model.addAttribute("order", order);
        model.addAttribute("goods", goods);

        return "order_detail";
    }
}
